package com.jeeww.activiti;

import java.util.List;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;

import com.jeeww.core.vo.Pager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeeww.core.CommonConstants;

/**
 * 工作流工具类.
 * @author jiangww
 */
public class ActivitiUtils {

    /**
     * 获取流程定义列表集合.
     * @param pager 流程定义查询结果对象.
     * @return 返回流程定义列表集合.
     */
    public static final String getProcessDefinitionGrid(final Pager<ProcessDefinition> pager) {
        JSONArray rows = new JSONArray();
        List<ProcessDefinition> processDefinitionList = pager.getResult();
        for (ProcessDefinition processDefinition : processDefinitionList) {
            JSONObject rowItem = new JSONObject();
            rowItem.put(ActivitiConstants.C_PROCESS_DEFINITION_ID, processDefinition.getId());
            rowItem.put(ActivitiConstants.C_PROCESS_KEY, processDefinition.getKey());
            rowItem.put(ActivitiConstants.C_PROCESS_NAME, processDefinition.getName());
            rowItem.put(ActivitiConstants.C_PROCESS_DESC, processDefinition.getDescription());
            rows.add(rowItem);
        }
        JSONObject result = new JSONObject();
        result.put(CommonConstants.TOTAL, pager.getResultCount());
        result.put(CommonConstants.ROWS, rows);
        return JSON.toJSONString(result);
    }

    /**
     * 获取流程定义列表集合.
     * @param pager 流程定义查询结果对象.
     * @return 返回流程定义列表集合.
     */
    public static final String getProcessInstanceGrid(final Pager<ProcessInstance> pager) {
        JSONArray rows = new JSONArray();
        List<ProcessInstance> processInstanceList = pager.getResult();
        for (ProcessInstance processInstance : processInstanceList) {
            JSONObject rowItem = new JSONObject();
            rowItem.put(ActivitiConstants.C_PROCESS_DEFINITION_ID, processInstance.getProcessDefinitionId());
            rowItem.put(ActivitiConstants.C_PROCESS_INSTANCE_ID, processInstance.getProcessInstanceId());
            rowItem.put(ActivitiConstants.C_PROCESS_IS_END, processInstance.isEnded());
            rowItem.put(ActivitiConstants.C_PROCESS_ACTIVITY_ID, processInstance.getActivityId());
            rowItem.put(ActivitiConstants.C_PROCESS_IS_SUSPENDED, processInstance.isSuspended());
            rows.add(rowItem);
        }
        JSONObject result = new JSONObject();
        result.put(CommonConstants.TOTAL, pager.getResultCount());
        result.put(CommonConstants.ROWS, rows);
        return JSON.toJSONString(result);
    }
}
